﻿using System;

namespace Kivensoft.XlsReader {
	public class Cell {
		public Cell(string value) { Value = value; }
		public Row Row { get; set; }
		public Column Column { get; set; }
		public NumberFormat Format { get; set; }

		private string value;
		public string Value { get { return value; } set { this.value = value; } }

		public int? AsInt {
			get {
				int i = 0;
				if (!string.IsNullOrEmpty(value) && int.TryParse(value, out i))
					return i;
				else return null;
			}
		}

		public double? AsDouble {
			get {
				double d = 0.0;
				if (!string.IsNullOrEmpty(value) && double.TryParse(value, out d))
					return d;
				else return null;
			}
		}

		public decimal? AsDecimal {
			get {
				decimal d = 0;
				if (!string.IsNullOrEmpty(value) && decimal.TryParse(value, out d))
					return d;
				else return null;
			}
		}

		public DateTime? AsDate {
			get {
				DateTime d;
				if (DateTime.TryParse(value, out d)) return d;
				return Utilities.ToDate(value, Row.Sheet.Workbook.BaseYear);
			}
		}

		public TimeSpan? AsTime {
			get {
				TimeSpan t;
				if (TimeSpan.TryParse(value, out t)) return t;
				return Utilities.ToTime(value);
			}
		}

		public DateTime? AsDateTime {
			get {
				DateTime d;
				if (DateTime.TryParse(value, out d)) return d;
				return Utilities.ToDateTime(value, Row.Sheet.Workbook.BaseYear);
			}
		}
	}
}
